#include "accelaratescale.h"
#include <QStringList>
#include <QtDebug>

AccelarateScale::AccelarateScale(QString port,QString baud,DataBitsType dataBits,ParityType parity,StopBitsType stopBits,QObject *parent) :
    QObject(parent)
{
    initComSetting( port, baud, dataBits, parity, stopBits);
    m_scaleTimer = new QTimer(0);
    m_scaleTimer->start(1000);
    connect(m_scaleTimer,SIGNAL(timeout()),this,SLOT(autoScaleSlots()));
}

AccelarateScale::~AccelarateScale()
{
    if (myCom != NULL) {
        if (myCom->isOpen()) {
            myCom->close();
        }
        delete myCom;
    }
}

AccelarateScale *AccelarateScale::m_instance = NULL;
AccelarateScale *AccelarateScale::getobj(QString port,QString baud,DataBitsType dataBits,ParityType parity,StopBitsType stopBits)
{
    if (m_instance ==  NULL) {
        m_instance = new AccelarateScale(port,baud,dataBits,parity,stopBits);
    }
    return m_instance;
}

void AccelarateScale::initComSetting(QString port,QString baud,DataBitsType dataBits,ParityType parity,StopBitsType stopBits)
{
    QString portName = port;   //获取串口名
    myCom = NULL;
#ifdef Q_OS_LINUX
    myCom = new QextSerialPort("/dev/" + portName);
#elif defined (Q_OS_WIN)
    if(m_scaleCom == NULL)
    {
        m_scaleCom = new QextSerialPort(portName);
    }
#endif
    connect(myCom, SIGNAL(readyRead()), this, SLOT(readScaleCom()));
    //设置波特率
    myCom->setBaudRate((BaudRateType)baud.toInt());//9600
    //设置数据流控制
    myCom->setFlowControl(FLOW_OFF);
    //设置延时
    myCom->setTimeout(50);
    //设置数据位
    myCom->setDataBits((DataBitsType)dataBits);//8
    //设置校验
    myCom->setParity(parity);//PAR_NONE
    myCom->setStopBits(stopBits);//STOP_1
    if(!myCom->isOpen()) {
        myCom->open(QIODevice::ReadWrite);
    }
}

void AccelarateScale::readScaleCom()
{
    if (myCom->bytesAvailable() > 0) {
       QByteArray readArray = myCom->readAll();
//       for (int i = 0; i < readArray.size(); i++) {

//       }
       QByteArray readArrayTemp = readArray.mid(3,readArray.length() - 4);
       if (readArrayTemp.at(0) == '0') {
           readArrayTemp = readArrayTemp.remove(0,1);
       }
       if (readArrayTemp.at(0) == '0') {
           readArrayTemp = readArrayTemp.remove(0,1);
       }
       QString distance = QString(readArrayTemp.trimmed());

       emit laserDistance(distance);
    }
}

void AccelarateScale::autoScaleSlots()
{
    QByteArray buf;
    QString str;
    bool ok;
    char data;
    QStringList list;
    str = "80 06 02 78";
    list = str.split(" ");
    for (int i = 0; i < list.count(); i++) {
        if(list.at(i) == " ")
            continue;
        if (list.at(i).isEmpty())
            continue;
        data = (char)list.at(i).toInt(&ok,16);
        buf.append(data);
    }
    myCom->write(buf);
}
